<template>
    <div class="ma-content-block lg:flex justify-between p-4">
        <div class="app-container">
            <div class="container-header">
                <div class="container-header-tr">
                    <div>
                        <span style="width: 40px" class="s1">{{
                            $t('basics.project')
                        }}</span>
                        <a-select
                            v-model="form.project_id"
                            :placeholder="$t('basics.textPro')"
                        >
                            <a-option
                                v-for="item in projectList"
                                :label="item.project_name"
                                :value="item.id"
                            ></a-option>
                        </a-select>
                    </div>
                    <div>
                        <span style="width: 40px" class="s1">{{
                            $t('basics.accName')
                        }}</span>
                        <a-input
                            v-model="form.username"
                            :placeholder="$t('basics.textAcc')"
                        />
                    </div>
                    <div>
                        <span class="s1">{{ $t('basics.status') }}</span>
                        <a-select
                            style="width: 120px"
                            v-model="form.status"
                            :placeholder="$t('basics.textStatus')"
                            allow-clear
                        >
                            <a-option
                                :label="$t('basics.zhengchang')"
                                :value="1"
                            ></a-option>
                            <a-option
                                :label="$t('basics.tingyong')"
                                :value="2"
                            ></a-option>
                        </a-select>
                    </div>
                    <div>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="searchButton"
                        >
                            <icon-search class="mr6" />
                            {{ $t('basics.search') }}
                        </a-button>
                        <a-button type="secondary" @click="resetButton">
                            <icon-refresh class="mr6" />
                            {{ $t('basics.reset') }}
                        </a-button>
                    </div>
                </div>
                <div class="container-header-tr mt10 mb10">
                    <div>
                        <a-button class="mr20" type="primary" @click="addAcc">
                            <icon-menu-fold class="mr6" />
                            {{ $t('basics.buhao') }}
                        </a-button>
                        <a-button class="mr20" type="primary" @click="bandPro">
                            <icon-menu-unfold class="mr6" />
                            {{ $t('basics.fasong') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="unbindPro(false)"
                        >
                            <icon-menu-unfold class="mr6" />
                            {{ $t('basics.releaseAccount') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="upKf(false)"
                        >
                            <icon-menu-unfold class="mr6" />
                            {{ $t('basics.assignAccount') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            status="danger"
                            @click="unbindPro(true)"
                        >
                            <icon-menu-unfold class="mr6" />
                            {{ $t('basics.bandBtn') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="exportToExcel"
                        >
                            导出excel
                        </a-button>
                    </div>
                </div>
            </div>
            <div class="container-content">
                <div class="container-content-table">
                    <a-table
                        summary-text="总计"
                        :columns="columns"
                        :data="tableList"
                        :loading="loading"
                        :row-selection="rowSelection"
                        v-model:selectedKeys="selectedKeys"
                        :summary="true"
                        row-key="id"
                        @selection-change="getRowData"
                        :pagination="false"
                    >
                        <template #status="{ record }">
                            <a-popconfirm
                                :content="
                                    $t('basics.confirmEdit') +
                                    (record.status == 1
                                        ? $t('basics.openTxt')
                                        : $t('basics.offTxt')) +
                                    $t('basics.whatTxt')
                                "
                                @ok="statusChange(record)"
                            >
                                <a-switch
                                    v-model="record.status"
                                    :checked-value="1"
                                    :unchecked-value="2"
                                />
                            </a-popconfirm>
                        </template>
                        <template #num_of_success="{ record }">
                            {{ record.num_of_assign_message }}/{{
                                record.num_of_success
                            }}
                        </template>
                        <template #num_of_reply="{ record }">
                            <span>{{ computerNum(record) }}</span>
                        </template>
                        <template #summary-cell="{ column, record, rowIndex }">
                            <template
                                v-if="column.dataIndex === 'num_of_success'"
                            >
                                <p v-if="tableList.length">
                                    {{
                                        tableList
                                            .map((n) => n.num_of_assign_message)
                                            .reduce(
                                                (a, b) => Number(a) + Number(b)
                                            )
                                    }}/{{
                                        tableList
                                            .map((n) => n.num_of_success)
                                            .reduce(
                                                (a, b) => Number(a) + Number(b)
                                            )
                                    }}
                                </p>
                            </template>
                            <template
                                v-else-if="column.dataIndex === 'num_of_reply'"
                            >
                                <p v-if="tableList.length">
                                    {{
                                        (
                                            tableList
                                                .map((n) =>
                                                    String(
                                                        computerNum(n)
                                                    ).replace('%', '')
                                                )
                                                .reduce(
                                                    (a, b) =>
                                                        Number(a) + Number(b)
                                                ) / tableList.length
                                        ).toFixed(2) + '%'
                                    }}
                                </p> </template
                            ><template
                                v-else-if="column.dataIndex === 'status'"
                            >
                            </template>
                            <template v-else>{{
                                record[column.dataIndex]
                            }}</template>
                        </template>
                    </a-table>
                    <div
                        class="_crud-footer mt-3 text-right"
                        ref="crudFooterRef"
                    >
                        <a-pagination
                            :total="pageList.total"
                            show-total
                            show-jumper
                            show-page-size
                            @page-size-change="getList"
                            @change="getList"
                            v-model:current="form.page"
                            v-model:page-size="form.pageSize"
                            style="display: inline-flex"
                            :page-size-options="[10, 20, 50, 100]"
                            :default-page-size="100"
                        />
                    </div>
                </div>
            </div>
            <a-modal
                v-model:visible="kf"
                :render-to-body="false"
                :footer="false"
            >
                <template #title> {{ $t('basics.fenpeishuliang') }} </template>
                <a-form :model="kfForm" ref="kfRef" :rules="kfrules">
                    <a-form-item
                        field="assgin_num"
                        :label="$t('basics.fenpeishuliang')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            style="width: 100%; margin-right: 20px"
                            v-model="kfForm.assgin_num"
                            type="number"
                            :min="0"
                            @keyup.enter="handleOk"
                        />
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button
                        style="color: #000"
                        class="mr20"
                        @click="handleCancel"
                        >{{ $t('basics.concel') }}</a-button
                    >
                    <a-button
                        class="mr20"
                        type="primary"
                        @click="handleKF"
                        style="margin-right: 20px"
                        >{{ $t('basics.sure') }}</a-button
                    >
                </div>
            </a-modal>
            <a-modal
                v-model:visible="visible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title>
                    {{ $t('basics.fasong') }}
                </template>
                <a-form :model="bandForm" ref="bandFormRef" :rules="rules">
                    <a-form-item
                        field="num_of_message_available"
                        :label="$t('basics.fasong')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            style="width: 100%; margin-right: 20px"
                            v-model="bandForm.num_of_message_available"
                            :placeholder="$t('basics.textFs')"
                            type="number"
                            :min="0"
                            @keyup.enter="handleOk"
                        />
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button
                        style="color: #000"
                        class="mr20"
                        @click="handleCancel"
                        >{{ $t('basics.concel') }}</a-button
                    >
                    <a-button class="mr20" type="primary" @click="handleOk">{{
                        $t('basics.sure')
                    }}</a-button>
                </div>
            </a-modal>
        </div>
    </div>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue';
import {
    getUserProjectList,
    changeStatus,
    setMessageAvailable,
    getProjectId,
    addReplenish,
    unbindPhoneinfo,
    batchChangeStatus,
    assignCustomerServices
} from '@/api/cloud/userProject.js';
import { getProjectList } from '@/api/cloud/client.js';
import { useI18n } from 'vue-i18n';
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import { formatDate } from '@/utils/common';

const { t } = useI18n();
const { proxy } = getCurrentInstance();
const bandFormRef = ref('');
const kf = ref(false);
const kfRef = ref([]);
const selectedKeys = ref([]);
const loading = ref(true);
const upKf = () => {
    if (!selectedKeys.value.length) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    kf.value = true;
};
const computerNum = (record) => {
    if (record.num_of_success) {
        let total =
            (
                (record.num_of_reply_conversion / record.num_of_success) *
                100
            ).toFixed(2) + '%';
        if (total > 100) {
            return 100 + '%';
        } else {
            return total;
        }
    } else {
        return 0;
    }
};

const data = ref([
    { name: 'Alice', email: 'alice@example.com' },
    { name: 'Bob', email: 'bob@example.com' }
]);

const exportToExcel = () => {
    let exportData = tableList.value.map((n) => {
        let obj = {};
        obj[t('basics.accName')] = n.username;
        obj[t('basics.createAt')] = n.created_at;
        obj[
            t('basics.sendSeccess')
        ] = `${n.num_of_assign_message}/${n.num_of_success}`;
        obj[t('basics.huifu')] = n.num_of_reply_conversion;
        obj[t('basics.huifuNum')] = computerNum(n);
        obj[t('basics.accNum')] = n.num_of_phoneinfo_available;
        obj[t('basics.accBan')] = n.num_of_phoneinfo_ban;
        obj[t('basics.riskControlAccounts')] = n.rick_control;
        obj[t('basics.status')] =
            n.status == 1 ? t('basics.openTxt') : t('basics.offTxt');

        return obj;
    });
    const ws = XLSX.utils.json_to_sheet(exportData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
    }

    saveAs(
        new Blob([s2ab(wbout)], { type: 'application/octet-stream' }),
        `${t('basics.userProject')}${formatDate(new Date())
            .split('-')
            .join('')
            .split(':')
            .join('')
            .split(' ')
            .join('')}.xlsx`
    );
};

const kfForm = ref({});
// 控制对话框
const visible = ref(false);
// 绑定项目表单
const bandForm = ref({});
const columns = [
    {
        title: t('basics.accName'),
        dataIndex: 'username',
        minWidth: 100,
        slotName: 'username'
    },
    {
        title: t('basics.createAt'),
        dataIndex: 'created_at',
        minWidth: 200
    },
    {
        title: t('basics.sendSeccess'),
        dataIndex: 'num_of_success',
        minWidth: 150,
        slotName: 'num_of_success'
    },
    {
        title: t('basics.huifu'),
        dataIndex: 'num_of_reply_conversion',
        minWidth: 150
    },
    {
        title: t('basics.huifuNum'),
        dataIndex: 'num_of_reply',
        minWidth: 150,
        slotName: 'num_of_reply'
    },
    {
        title: t('basics.accNum'),
        dataIndex: 'num_of_phoneinfo_available',
        minWidth: 150
    },
    {
        title: t('basics.accBan'),
        dataIndex: 'num_of_phoneinfo_ban',
        minWidth: 150
    },
    {
        title: t('basics.riskControlAccounts'),
        dataIndex: 'rick_control',
        minWidth: 150
    },
    {
        title: t('basics.status'),
        dataIndex: 'status',
        minWidth: 150,
        slotName: 'status'
    }
];

const form = ref({
    username: '',
    phone: '',
    project_id: '',
    status: '',
    page: 1,
    pageSize: 100
});
const kfrules = ref({
    assgin_num: [
        {
            required: true,
            message: t('basics.bitian')
        }
    ]
});
const rules = ref({
    num_of_message_available: [
        {
            required: true,
            message: t('basics.num_of_message_warn')
        }
    ]
});
const tableList = ref([]);
const pageList = ref({
    total: 0
});
const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
});

const spanMethod = (tableData) => {
    console.log(tableData);
    let { rowIndex, columnIndex, column, record } = tableData;
    let { dataIndex } = column;
    console.log(dataIndex);
    switch (dataIndex) {
        case 'num_of_success':
            return {
                colspan: 1,
                record: {
                    num_of_success: 1
                }
            };

        default:
            return {
                colspan: 1
            };
    }

    // if (rowIndex === 0 && columnIndex === 1) {
    //     return {
    //         colspan: 2
    //     };
    // }
};

// 补号
const addAcc = () => {
    if (!selectedKeys.value.length) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    addReplenish({ user_project_ids: selectedKeys.value }).then((res) => {
        if (res.code == 200) {
            selectedKeys.value = [];
            checkBoxList.value = [];
            proxy.$message.success(t('basics.replenish'));
            getList();
        }
    });
};
// 获取美国短信id
const getId = () => {
    getProjectId({ project_key: 'america' }).then((res) => {
        if (res.data) {
            form.value.project_id = res.data.id;
            getList();
        }
    });
};

// 获取列表数据
const getList = () => {
    getUserProjectList(form.value).then((res) => {
        tableList.value = res.data.items;
        pageList.value = res.data.pageInfo;
        loading.value = false;
    });
};

// 获取项目列表
const projectList = ref([]);
const getProject = () => {
    getProjectList().then((res) => {
        projectList.value = res.data.items;
        if (res.data.items && res.data.items.length > 0) {
        }
    });
};

// 搜索
const searchButton = () => {
    getList();
};
const checkBoxList = ref([]);
// 获取选择列
const getRowData = (selectedRowKeys) => {
    checkBoxList.value = tableList.value
        .filter((item) => selectedRowKeys.includes(item.id))
        .map((i) => {
            return i.user_id;
        });
};

const reset = () => {
    form.value.username = '';
    form.value.phone = '';
    form.value.status = '';
    form.value.page = 1;
    form.value.pageSize = 100;
};

const resetButton = () => {
    reset();
    getList();
};
// 状态改变
const statusChange = (row) => {
    let nowStatus = row.status == 1 ? 1 : 2;
    changeStatus({
        user_id: row.user_id,
        project_id: row.project_id,
        status: nowStatus
    })
        .then((res) => {
            if (res.code == 200) {
                proxy.$message.success(t('basics.updataSecc'));
            }
        })
        .catch((error) => {
            row.status = row.status == 1 ? 2 : 1;
        });
};

const bandPro = () => {
    if (!selectedKeys.value.length) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    visible.value = true;
};
const unbindPro = (isBand) => {
    if (!selectedKeys.value.length) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    if (isBand) {
        batchChangeStatus({
            user_ids: checkBoxList.value,
            project_id: form.value.project_id,
            status: 2
        }).then((res) => {
            if (res.code == 200) {
                selectedKeys.value = [];
                checkBoxList.value = [];
                getList();
                proxy.$message.success(t('basics.updataSecc'));
            }
        });
    } else {
        unbindPhoneinfo({
            user_ids: checkBoxList.value,
            project_id: form.value.project_id
        }).then((res) => {
            checkBoxList.value = [];
            selectedKeys.value = [];
            proxy.$message.success(
                t('basics.successfullyReleased') +
                    res.data.count +
                    t('basics.individual')
            );
        });
    }
};
const handleKF = () => {
    proxy.$refs['kfRef'].validate((valid) => {
        if (!valid) {
            assignCustomerServices({
                user_project_ids: selectedKeys.value,
                assign_num: kfForm.value.assgin_num,
                project_id: form.value.project_id
            })
                .then((res) => {
                    if (res.code == 200) {
                        kf.value = false;
                        selectedKeys.value = [];
                        checkBoxList.value = [];
                        proxy.$message.success('分配成功');
                        getList();
                    }
                })
                .catch(() => {
                    getList();
                    kf.value = false;
                });
        }
    });
};
const handleOk = () => {
    proxy.$refs['bandFormRef'].validate((valid) => {
        if (!valid) {
            setMessageAvailable({
                ids: selectedKeys.value,
                num_of_message_available:
                    bandForm.value.num_of_message_available,
                project_id: form.value.project_id
            })
                .then((res) => {
                    if (res.code == 200) {
                        visible.value = false;
                        selectedKeys.value = [];
                        checkBoxList.value = [];
                        getList();
                    }
                })
                .catch(() => {
                    getList();
                    visible.value = false;
                });
        }
    });
};
const handleCancel = () => {
    visible.value = false;
    kf.value = false;
};

getId();
getProject();
</script>
<script>
export default { name: 'cloud:userProject' };
</script>
<style lang="less" scoped>
@import url('@/style/layout.less');
::v-deep .arco-table-container {
    background-color: @th-bg-color;
}
::v-deep .arco-table tfoot .arco-table-td {
    background-color: @td-bg-color;
}
</style>
